package com.abocode.aichat.server.context.delivery.inbound;


import com.abocode.aichat.api.ReplayResultBuilder;
import com.abocode.aichat.server.context.delivery.AbstractServerDeliver;
import com.abocode.aichat.api.ReplayResult;
import com.abocode.aichat.data.Entity;
import com.abocode.aichat.server.context.delivery.reply.Replies;
import com.abocode.aichat.server.context.delivery.reply.Reply;
import com.abocode.aichat.data.MessageStanza;
import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;

/**
 * @author guanxf
 */
@Slf4j
public class InboundServerDeliver extends AbstractServerDeliver<Replies> {


    class InboundReplyCallable implements Callable<ReplayResult> {
        public Channel channel;

        public MessageStanza stanza;

        public InboundReplyCallable(Channel channel, MessageStanza stanza) {
            this.channel = channel;
            this.stanza = stanza;
        }

        @Override
        public ReplayResult call() {
            try {
                String replyStr = JSON.toJSONString(stanza);
                Entity entity = stanza.findTo();
                if (entity != null) {
                    String domain = getServerRuntimeContext().getProtocolChannelRegistry().domain(entity);
                    log.info("domain:" + domain + "replyStr:" + replyStr);
                    if (domain != null && !getServerRuntimeContext().validateDomain(domain)) {
                        getServerRuntimeContext().getMessagePipeline().sendMessageToChannel(replyStr, domain);
                    } else {
                        channel.writeAndFlush(replyStr).sync();
                    }
                } else {
                    channel.writeAndFlush(replyStr).sync();
                }
            } catch (Exception ex) {
                log.error("call Exception", ex);
                return ReplayResultBuilder.failure();
            }
            return ReplayResultBuilder.success();

        }
    }

    @Override
    public void deliver(Replies replies, MessageStanza stanza) {
        if (replies == null) {
            return;
        }
        for (Reply reply : replies.getReplies()) {
            for (Channel channel : reply.getChannels()) {
                if (reply.getMessageStanza() != null) {
                    executor.submit(new InboundReplyCallable(channel, reply.getMessageStanza()));
                } else {
                    throw new RuntimeException("未实现");
                }
            }
        }
    }

}
